#include "buddylist.h"

#include <QtDebug>
#include <QStringList>

using namespace Playur;
using namespace Irc;

BuddyList::BuddyList(const QString& ident, const QString& _address)
        : address(_address)
{
    nick = ident.split('@').at(0);
    server = ident.split('@').at(1);

    session = new Session(this);

    connect(session, SIGNAL(connected()), this, SLOT(connected()));
    connect(session, SIGNAL(msgJoined(const QString&, const QString&)),
            this, SLOT(msgJoined(const QString&, const QString&)));
    connect(session, SIGNAL(msgParted(const QString&, const QString&, const QString&)),
            this, SLOT(msgParted(const QString&, const QString&, const QString&)));
    connect(session, SIGNAL(msgQuit(const QString&, const QString&)),
            this, SLOT(msgQuit(const QString&, const QString&)));
    connect(session, SIGNAL(msgMessageReceived(const QString&, const QString&, const QString&)),
            this, SLOT(msgMessageReceived(const QString&, const QString&, const QString&)));

    session->setNick(nick);
    session->setIdent("playur");
    session->connectToServer(server);
}

void BuddyList::connected()
{
    //qDebug() << "connected";
    session->join("#playur");
    session->names("#playur");
}

const QMap<QString, QString> BuddyList::get()
{
    return addresses;
}

void BuddyList::msgJoined(const QString& origin, const QString& channel)
{
    //qDebug() << "msgJoined(" << origin << ", " << channel << ")";
    if (channel != "#playur")
        return;

    if (origin == nick)
        session->cmdMessage("#playur", QString("ADDR ") + address);
    else
        session->cmdMessage(origin, QString("ADDR ") + address);
}

void BuddyList::msgParted(const QString& origin, const QString& channel, const QString& mesg)
{
    //qDebug() << "msgParted(" << origin << ", " << channel << ", " << mesg << ")";
    addresses.remove(origin);
    qDebug() << origin << "has parted";
    emit buddyDisconnected(origin);
}

void BuddyList::msgQuit(const QString& origin, const QString& channel)
{
    //qDebug() << "msgQuit(" << origin << ", " << channel << ")";
    addresses.remove(origin);
    qDebug() << origin << "has quit";
    emit buddyDisconnected(origin);
}

void BuddyList::msgMessageReceived(const QString& origin, const QString& receiver, const QString& message)
{
    //qDebug() << "message(" << origin << ", " << receiver << ", " << message << ")";
    if (origin == nick)
        return;

    if (receiver == origin || receiver == "#playur")
        if (message.startsWith("ADDR "))
        {
            addresses[origin] = message.split(" ").at(1);
            qDebug() << origin << "is" << addresses[origin];
            emit buddyConnected(origin);
        }
}

